<template>
  <div class="global-box">
    <div class="title">
      <h1>{{ title }}</h1>
      <a-button type="primary" @click="addLearning('add')">添加学习包</a-button>
    </div>
    <a-card :body-style="{ padding: '24px' }" :bordered="false">
      <div class="form-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-item label="课程目录">
                <a-cascader
                  :field-names="{ label: 'value', value: 'id', children: 'children' }"
                  :options="directoryOptions"
                  :load-data="loadData"
                  placeholder="请选择课程目录"
                  change-on-select
                  v-model="queryParam.directory"
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="学习包ID">
                <a-input v-model="queryParam.id" placeholder="请输入学习包ID" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="学习包名称">
                <a-input v-model="queryParam.name" placeholder="请输入学习包名称" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="操作人">
                <a-input
                  v-model="queryParam.operator"
                  @keyup="numbers"
                  placeholder="请输入操作人"
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <span class="table-page-search-submitButtons" style="float: left">
                <a-upload
                  name="file"
                  :show-upload-list="false"
                  :before-upload="addBeforeUpload"
                  :customRequest="addHandleChange"
                >
                  <a-button><a-icon type="upload" />批量导入</a-button>
                </a-upload>
              </span>
            </a-col>
            <a-col :md="18" :sm="24">
              <span class="table-page-search-submitButtons" style="float: right">
                <a-button type="primary" @click="search">筛选</a-button>
                <a-button style="margin-left: 8px" @click="reset">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div class="table-wrapper">
        <a-table
          :columns="columns"
          :data-source="data"
          :pagination="pagination"
          :rowKey="record => record.studyPackageId"
        >
          <span slot="action" slot-scope="text, record">
            <template>
              <a @click="handleCopy(record)">复制</a>
              <a-divider type="vertical" />
              <a @click="handleLook(record)">查看</a>
              <a-divider type="vertical" />
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm
                placement="top"
                ok-text="删除"
                cancel-text="取消"
                @confirm="handleDelete(record)"
                v-if="record.isPackageStudy"
              >
                <template slot="title">
                  <p>有商品正在使用该学习包，是否确认删除？</p>
                  <p style="color: #999">已购买包含该学习包的学员无法再查看</p>
                </template>
                <a>删除</a>
              </a-popconfirm>
              <a-popconfirm
                placement="top"
                ok-text="确认"
                cancel-text="取消"
                @confirm="handleDelete(record)"
                v-else
              >
                <template slot="title">
                  <p>你确定要删除该学习包吗？</p>
                </template>
                <a>删除</a>
              </a-popconfirm>
              <a-divider type="vertical" />
              <a-popconfirm
                placement="top"
                ok-text="确认"
                cancel-text="取消"
                @confirm="handleToggle(record)"
                v-if="record.activeStatus == '启用'"
              >
                <template slot="title">
                  <p>你确定要禁用该学习包吗？</p>
                </template>
                <a>禁用</a>
              </a-popconfirm>
              <a @click="handleToggle(record)" v-else>启用</a>
            </template>
          </span>
        </a-table>
      </div>
    </a-card>
  </div>
</template>

<script>
import { directory, list, disable, deletes, bulkImport } from '@/api/product/learning'
const columns = [
  {
    title: '学习包ID',
    dataIndex: 'studyPackageId',
    align: 'center'
  },
  {
    title: '学习包名称',
    dataIndex: 'studyPackageName',
    align: 'center'
  },
  {
    title: '学习包价格',
    dataIndex: 'studyPackagePrice',
    align: 'center'
  },
  {
    title: '操作人',
    dataIndex: 'operatorUserName',
    align: 'center'
  },
  {
    title: '操作时间',
    dataIndex: 'operatorTime',
    align: 'center'
  },
  {
    title: '学习包状态',
    dataIndex: 'activeStatus',
    align: 'center'
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' },
    align: 'center'
  }
]
export default {
  data () {
    return {
      title: '学习包管理',
      queryParam: {
        directory: [],
        id: '',
        name: '',
        operator: ''
      },
      columns,
      data: [],
      pagination: {
        defaultCurrent: 1, // 默认当前页数
        defaultPageSize: 10, // 默认当前页显示数据的大小
        total: 0, // 总数，必须先有
        showSizeChanger: true,
        showQuickJumper: true,
        onShowSizeChange: (current, pageSize) => {
          this.pagination.defaultCurrent = 1
          this.pagination.defaultPageSize = pageSize
          this.getData()
        },
        // 改变每页数量时更新显示
        onChange: (current, size) => {
          this.pagination.defaultCurrent = current
          this.pagination.defaultPageSize = size
          this.getData()
        }
      },
      directoryOptions: [],
      labelCol: { span: 10 },
      wrapperCol: { span: 14 }
    }
  },
  computed: {
  },
  mounted () {
    this.getDirectory()
    this.getData()
  },
  methods: {
    // 限制排序只能输入数字
    numbers () {
      this.queryParam.operator = this.queryParam.operator.replace(/\D/g, '')
    },
    // 获取学习包列表数据
    getData () {
      const data = {
        currentPage: this.pagination.defaultCurrent,
        pageSize: this.pagination.defaultPageSize
      }
      if (this.queryParam.id !== '') {
        data.studyPackageId = this.queryParam.id
      }
      if (this.queryParam.name !== '') {
        data.studyPackageName = this.queryParam.name
      }
      if (this.queryParam.operator !== '') {
        data.operatorUserGroupId = this.queryParam.operator
      }
      if (this.queryParam.directory[0]) {
        data.directoryId = this.queryParam.directory[0]
      }
      if (this.queryParam.directory[1]) {
        data.examId = this.queryParam.directory[1]
      }
      if (this.queryParam.directory[2]) {
        data.subjectId = this.queryParam.directory[2]
      }
      if (this.queryParam.directory[3]) {
        data.fourExamId = this.queryParam.directory[3]
      }
      if (this.queryParam.directory[4]) {
        data.fiveExamId = this.queryParam.directory[4]
      }
      if (this.queryParam.directory[5]) {
        data.sixExamId = this.queryParam.directory[5]
      }
      list(data).then(res => {
        if (res.code === '1') {
          this.pagination.total = res.data.totalSize
          this.data = res.data.rows
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 添加学习包
    addLearning () {
      this.$router.push({
        name: 'productLearningCommon'
      })
    },
    // 表格编辑
    handleEdit (record) {
      this.$router.push({
        name: 'productLearningCommon',
        params: {
          studyPackageId: record.studyPackageId,
          edit: true
        }
      })
    },
    // 表格复制
    handleCopy (record) {
      this.$router.push({
        name: 'productLearningCommon',
        params: {
          studyPackageId: record.studyPackageId,
          edit: false
        }
      })
    },
    // 表格删除
    handleDelete (record) {
      const data = {
        studyPackageId: record.studyPackageId
      }
      deletes(data).then(res => {
        if (res.code === '1') {
          this.$message.success(res.msg)
          this.getData()
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 表格查看内容
    handleLook (record) {
      this.$router.push({
        name: 'productLearningView',
        params: {
          studyPackageId: record.studyPackageId
        }
      })
    },
    // 表格启用禁用
    handleToggle (record) {
      const data = {
        studyPackageId: record.studyPackageId,
        isActive: record.activeStatus === '禁用' ? 0 : 1
      }
      disable(data).then(res => {
        if (res.code === '1') {
          this.$message.success(res.msg)
          this.getData()
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 批量导入
    addBeforeUpload (file) {
      const isJpgOrPng = file.type.indexOf('excel') !== -1
      if (!isJpgOrPng) {
        this.$message.error('请选择正确的文件格式')
      }
      return isJpgOrPng
    },
    addHandleChange (info) {
      this.fileList = info.fileList
      const formdata = new FormData()
      formdata.append('file', info.file)
      if (this.queryParam.directory[0]) {
        formdata.append('directoryId', this.queryParam.directory[0])
      }
      if (this.queryParam.directory[1]) {
        formdata.append('examId', this.queryParam.directory[1])
      }
      if (this.queryParam.directory[2]) {
        formdata.append('fiveExamId', this.queryParam.directory[2])
      }
      if (this.queryParam.directory[3]) {
        formdata.append('fourExamId', this.queryParam.directory[3])
      }
      if (this.queryParam.directory[4]) {
        formdata.append('sixExamId', this.queryParam.directory[4])
      }
      if (this.queryParam.directory[5]) {
        formdata.append('subjectId', this.queryParam.directory[5])
      }
      bulkImport(formdata).then(res => {
        if (res.code === '1') {
          this.$message.success(res.msg)
          this.getData()
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 筛选
    search () {
      this.getData()
    },
    // 重置
    reset () {
      this.queryParam = {
        directory: [],
        id: '',
        name: '',
        operator: ''
      }
      this.getData()
    },
    // 获取课程目录
    getDirectory () {
      const data = {
        type: 0,
        directoryLevel: 1
      }
      directory(data).then(res => {
        if (res.code === '1') {
          res.data.forEach(item => {
            item.isLeaf = false
          })
          this.directoryOptions = res.data
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 课程目录二级-六级
    loadData (selectedOptions) {
      const targetOption = selectedOptions[selectedOptions.length - 1]
      const data = {
        type: 1,
        parentId: targetOption.id,
        directoryLevel: 2
      }
      targetOption.loading = true
      directory(data).then(res => {
        if (res.code === '1') {
          if (res.data.length > 0) {
            res.data.forEach(item => {
              item.isLeaf = false
            })
            targetOption.loading = false
            targetOption.children = [...res.data]
          } else {
            targetOption.loading = false
            this.$message.error('暂无更多数据')
          }
        } else {
          targetOption.loading = false
          this.$message.error(res.msg)
        }
        this.directoryOptions = [...this.directoryOptions]
      }).catch(err => {
        this.$message.error(err.msg)
        targetOption.loading = false
      })
    }
  }
}
</script>
<style lang="less" scoped>
.form-status-tip {
  text-align: center;
  color: #999;
}
</style>
